<?php
namespace app;

use Exception;
use mysqli;

/**
 *
 */
class RestoreMySQL
{
    private $DB_HOST = '127.0.0.1'; // 数据库主机名
    private $DB_USER = 'root'; // 数据库用户名
    private $DB_PASS = 'root'; // 数据库密码
    private $DB_NAME = 'bishe'; // 数据库名
    private $sql_file = ''; // SQL 文件路径

    function __construct($db_host, $db_user, $db_pass, $db_name, $sql_file)
    {
        $this->DB_HOST = $db_host;
        $this->DB_USER = $db_user;
        $this->DB_PASS = $db_pass;
        $this->DB_NAME = $db_name;
        $this->sql_file = $sql_file;
    }

    // 还原数据库
    function restore()
    {
        $mysqli = new mysqli($this->DB_HOST, $this->DB_USER, $this->DB_PASS);
        if (mysqli_connect_errno()) {
            throw new Exception("Connect failed: " . mysqli_connect_error());
        }

        // 删除旧数据库（如果存在）
        $mysqli->query("DROP DATABASE IF EXISTS " . $this->DB_NAME);
        // 创建新数据库
        $mysqli->query("CREATE DATABASE " . $this->DB_NAME);
        // 选择新数据库
        $mysqli->select_db($this->DB_NAME);

        // 读取 SQL 文件并执行
        $sql = file_get_contents($this->sql_file);
        if (!$sql) {
            throw new Exception("无法读取 SQL 文件");
        }

        // 执行 SQL 语句
        if ($mysqli->multi_query($sql)) {
            while ($mysqli->more_results() && $mysqli->next_result()) {
                // 循环执行多语句查询
            }
            if ($mysqli->errno) {
                throw new Exception("SQL 执行错误: " . $mysqli->error);
            }
            // echo "数据库已还原";
        } else {
            throw new Exception("SQL 执行错误: " . $mysqli->error);
        }

        $mysqli->close();
        return true;
    }
}
